//ICC-AVR application builder : 2008-4-20 15:50:59
// Target : m168
// Crystal: 8.0000Mhz

//#include <iom168v.h>
//#include <macros.h>
//#include <avr/interrupt.h>
//#include "pwm.h"
#include "main.h"
#include <avr/io.h>

void port_init(void)
{
 PORTB = 0x00;
 DDRB  = 0x0e;
 PORTC = 0xFF; //m103 output only
 DDRC  = 0x04;
 PORTD = 0xFF;
 DDRD  = 0x1E;
}
//M168
/*
void timer0_init(void)
{
 TCCR0B = 0x00; //stop
 TCNT0 = 0x83; //set count
 TCCR0A = 0x00; 
 TCCR0B = 0x04; //start timer
 TIMSK0 = 0x01;
}*/
//m8 8M/256 4mS
void timer0_init(void)
{
 TCCR0 = 0x00; //stop
 TCNT0 = (uint8)(256-F_CPU/8/25000);//0x83; //set count
 TCCR0 = (1<<CS01); //start timer div 8
 TIMSK |= (1<<TOIE0);
}
//m8 8M/256 4mS
void timer1_init(void)
{
	TCCR1A=0;
	TCNT1 = (uInt)(65536-F_CPU/8/400); //400Hz
	TCCR1B = (1<<CS11);//div8
	TIMSK |= (1<<TOIE1);
}
//UART0 initialize
// desired baud rate: 115200
// actual: baud rate:111111 (3.7%)
// char size: 9 bit
// parity: Disabled
//m168
/*
void uart0_init(void)
{
 UCSR0B = 0x00; //disable while setting baud rate
 UCSR0A = (1<<U2X0);//double speed;
 UCSR0C = (1<<UCSZ00)|//9bit
		    (1<<UCSZ01);
		    
 UBRR0L = 3;//Fosc/(8*250*1000)-1; //set baud rate 250K
 UBRR0H = 0x00; //set baud rate hi
 UCSR0B = 
		   (1<<RXCIE0)|//0x9C;
		   (1<<RXEN0)|
		   (1<<TXEN0)|
		   //(1<<UPM00)
		   (1<<UCSZ02)
		   ;
 DDRD &= ~(1<<PD0);
 DDRC |= (1<<PC0);PORTC &= ~(1<<PC0);
}*/
//m8
void uart0_init(void)
{
 //uint16_t i;
 UCSRB = 0x00; //disable while setting baud rate
 UCSRA = (1<<U2X);//double speed;

 UCSRC &= ~(1<<URSEL);
 //i=3;//Fosc/(8*9600)-1;
 UBRRL = 3; //set baud rate 250K
 UBRRH = 0; //set baud rate hi
 UCSRB = 
		   (1<<RXCIE)|//0x9C;
		   (1<<RXEN)|
		   (1<<TXEN)|
		   //(1<<UPM00)
		   (1<<UCSZ2)
		   ;
 //UCSRC |= (1<<URSEL);
 UCSRC = (1<<URSEL)|
		 (1<<UCSZ0)
		 |(1<<UCSZ1)
		 //|(1<<USBS)
		 ;
 //DDRD &= ~(1<<PD0);
 DDRC |= (1<<PC0);PORTC &= ~(1<<PC0);
}
/*
#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
 //uart has received a character in UDR
}
*/
//call this routine to initialize all peripherals
void init_devices(void)
{
 cli(); //disable all interrupts
 port_init();
 uart0_init();
 timer0_init();
 timer1_init();
// PWM1_init();
// PWM2_init();
  //timer 0 interrupt sources
  sei(); //re-enable interrupts
}

